package com.example.quanxin.config;/*
 *
 *   welcome:11311
 *   创建时间:2023/6/3
 *
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.quanxin.entity.LoginParam;
import com.example.quanxin.service.ApiService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class StartListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private ApiService apiService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        OkHttpClient anotherClient = apiService.anotherClient;
        JSONObject jsonObject = new JSONObject();
        try {
            apiService.getAndStoreCookies(new LoginParam());
            jsonObject.put("username", "15922519663");
            jsonObject.put("password", "tym198563");
            jsonObject.put("role", "Teacher");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        //MediaType  设置Content-Type 标头中包含的媒体类型值
//        RequestBody requestBody = FormBody.create(jsonObject.toString(), MediaType.parse("application/json; charset=utf-8"));
//
//        Request request = new Request.Builder()
////                .url("https://ps-training.fuchuan.host/api/user/login")
//                .url("https://passport2.chaoxing.com/fanyalogin")
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")
//                .post(requestBody)
//                .build();
//        try(Response response = anotherClient.newCall(request).execute()) {
//            String string = response.body().string();
//            com.alibaba.fastjson.JSONObject result = JSON.parseObject(string);
//            GlobalConfig.globalToken = result.getString("token");
//        }catch (Exception e){
//            log.info("错误为{}",e);
//            throw new RuntimeException("登录错误");
//        }
    }
}
